<template>
  <div class="login">
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 登录数据表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.phone"
        name="手机号"
        label="请输入手机号"
        placeholder="手机号"
        :rules="[
          {
            required: true,
            message: '请填写手机号'
          },
          {
            validator: phoneCheck,
            message: '请输入正确手机号'
          }
        ]"
      />
      <van-field
        v-model="form.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          {
            required: true,
            message: '请填写密码'
          },
          {
            validator: psdCheck,
            message: '请填写正确的密码'
          }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
        >提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/services/user'

export default {
  name: 'login',
  data () {
    return {
      form: {
        phone: '',
        password: ''
      },
      // 登录加载状态确定
      isLoading: false
    }
  },
  methods: {
    phoneCheck (values) {
      return /^1\d{10}$/.test(values)
    },
    psdCheck (val) {
      return /^[a-zA-Z0-9]{6,12}$/.test(val)
    },
    onClickLeft () {
      this.$router.go(-1)
    },
    async onSubmit () {
      this.isLoading = true
      const { data } = await login(this.form)
      if (data.state === 1) {
        this.$toast.success('登陆成功')
        // 在获取到用户信息中时，存储到state中
        this.$store.commit('setUser', data.content)
        // 跳转到来时的页面
        this.$router.push(this.$route.query.redirect || '/')
      } else {
        this.$toast.fail('登陆失败')
      }
      this.isLoading = false
    }
  }
}
</script>

<style scoped>

</style>
